require('es6-promise').polyfill();

import axios from 'axios'

function createSysUserData(data){
  return {
    type:'CREATE_SYSUSER_DATA',
    data,
    date:Date.now()
  };
}

export function createSysUserDataAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/create',data).then(
      resp => dispatch(loadSysUserDataAsync({})),
      error => dispatch(createSysUserData([]))
    );
  };
}


function editSysUserData(data){
  return {
    type:'EDIT_SYSUSER_DATA',
    data,
    date:Date.now()
  };
}

export function editSysUserDataAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/update',data).then(
      resp => dispatch(loadSysUserDataAsync({})),
      error => dispatch(editSysUserData([]))
    );
  };
}


function deleteSysUserData(id) {
  return {
    type: 'DELETE_SYSUSER_DATA',
    id
  };
}

export function deleteSysUserDataAsync(id){
  return function(dispatch) {
    return axios.post('/api/sysuser/delete', {id: id}).then(
      resp => dispatch(loadSysUserDataAsync({})),
      error => dispatch(deleteSysUserData([]))
    );
  };
}


export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}


function loadSysUserData(data) {
  // console.log(data)
  return {
    type: 'LOAD_SYSUSER_DATA',
    data
  }
}

export function loadSysUserDataAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser',data).then(
      resp => dispatch(loadSysUserData(resp.data)),
      error => dispatch(loadSysUserData([]))
    );
  };
}

export function loadSysUserDataByPropertyAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/querySysUsersByProperty',data).then(
      resp => dispatch(loadSysUserData(resp.data)),
      error => dispatch(loadSysUserData([]))
    );
  };
}


export function changeSysUserPasswordAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/setPassword', data)
    .then(function(response) {
      if (response.data.success) {
        dispatch(apiMsgAction("提交成功"))
      }
      else {
        dispatch(apiMsgAction(response.data.errMsg))
      }
    })
    .catch(function(error) {
      dispatch(apiMsgAction(error.data.errMsg))
    })
  }
}
